﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace Common
{
    public static class AssemblyHelper
    {
        public enum ePlatform { Error, AnyCPU, x86, x64, IA64 };

        public static string GetBasePath()
        {
            return System.IO.Path.GetDirectoryName(GetCallingAssembly().CodeBase).Substring(6); ;
        }

        public static string GetExeLocation()
        {
            return System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        }

        public static string Location()
        {
            return GetCallingAssembly().Location;
        }

        public static String GetMethodName()
        {
            StackTrace st = new StackTrace();
            return st.GetFrame(1).GetMethod().Name;
        }

        public static Assembly GetCallingAssembly()
        {
            StackTrace st = new StackTrace();
            return st.GetFrame(2).GetMethod().Module.Assembly;
        }

        public static Assembly GetAssembly()
        {
            return GetCallingAssembly();
        }

        public static Version GetVersion()
        {
            return GetVersion(GetCallingAssembly());
        }

        public static Version GetVersion(Assembly assembly)
        {
            return assembly.GetName().Version;
        }

        public static string GetName()
        {
            return GetName(GetCallingAssembly());
        }

        public static string GetName(Assembly assembly)
        {
            foreach (Attribute attribute in Attribute.GetCustomAttributes(assembly))
            {
                if (attribute is AssemblyTitleAttribute)
                    return ((AssemblyTitleAttribute)attribute).Title;
            }

            return assembly.GetName().Name;
        }

        public static ePlatform GetArchitecture()
        {
            return GetArchitecture(GetCallingAssembly());
        }

        public static ePlatform GetArchitecture(Assembly assembly)
        {
            PortableExecutableKinds peKind;
            ImageFileMachine machine;

            assembly.ManifestModule.GetPEKind(out peKind, out machine);

            if (peKind == PortableExecutableKinds.ILOnly)
                return ePlatform.AnyCPU;
            if (machine == ImageFileMachine.I386)
                return ePlatform.x86;
            if (machine == ImageFileMachine.AMD64)
                return ePlatform.x64;
            if (machine == ImageFileMachine.IA64)
                return ePlatform.IA64;

            return ePlatform.Error;
        }
    }
}
